package com.atguigu.mybatisplus.service.impl;

import com.atguigu.mybatisplus.entity.User;
import com.atguigu.mybatisplus.mapper.UserMapper;
import com.atguigu.mybatisplus.service.UserService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;

/**
 * @author MI
 * @version 1.0
 * @date 2021/4/27 21:43
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,
    // 可以让事物在遇到非运行时异常时也回滚
    // @Transactional(rollbackFor = Exception.class)
    // @Transactional()//
    @Override
    public void error() throws Exception {

        // User user = new User();
        // user.setAge(28);
        // user.setEmail("grq@grq.com");
        // user.setCreateTime(LocalDateTime.now());
        // user.setName("grq");
        // this.save(user);
        ((UserService) AopContext.currentProxy()).updateMy();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void ds() {
        User user = new User();
        user.setAge(28);
        user.setEmail("grq@grq.com");
        user.setCreateTime(LocalDateTime.now());
        user.setName("grq");
        this.save(user);
        this.updateMy();
        // throw new RuntimeException("发生异常了..");
    }

    /**
     * 若同一类中的其他没有@Transactional 注解的方法内部调用有@Transactional 注解的方法，
     * 有@Transactional 注解的方法的事务被忽略，不会发生回滚。
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateMy() {
        User byId = this.getById(1);
        System.out.println(byId);
        byId.setAge(byId.getAge() + 1);
        this.updateById(byId);
        // updateTextTx();
        throw new RuntimeException("发生异常了..");
    }

    @Override
    public void sync() {
        CompletableFuture.runAsync(() -> {
            User ts = new User().setAge(28).setEmail("ss.com").setName("testAop");
            System.out.println(ts);
            save(ts);
            System.out.println(1 / 0);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTextTx() {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<User>();
        updateWrapper.eq(User::getId, 1L);
        updateWrapper.set(User::getName, "A");
        updateWrapper.set(User::getUpdateTime, LocalDateTime.now());
        this.update(updateWrapper);
        int a = 1 / 0;


    }
}
